package com.it.commicity.utils;


import com.it.commicity.common.ResultCodeEnum;
import com.it.commicity.config.exception.TokenException;
import com.it.commicity.domain.po.SysUser;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtils {
    // token时效：24小时
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    // 签名哈希的密钥，对于不同的加密算法来说含义不同
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
    private static final String TOKEN_PREFIX = "Bearer ";
    /**
     * 根据用户id和昵称生成token
     *
     * @param id       用户id
     * @param username 用户姓名
     * @return JWT规则生成的token
     */
    public static String getJwtToken(String id, String username) {
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("baobao-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id)
                .claim("username", username)
                // HS256算法实际上就是MD5加盐值，此时APP_SECRET就代表盐值
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    // 安全解析Token（适配旧版）
    private static Jws<Claims> parseToken(String jwtToken) throws JwtException {
        // 1. 清理非法字符和控制字符
        String cleanedToken = jwtToken.replaceAll("[^\\x20-\\x7E]", "");

        // 2. 使用旧版API解析
        return Jwts.parser()
                .setSigningKey(APP_SECRET)
                .parseClaimsJws(cleanedToken);
    }

    // 检查Token有效性
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            parseToken(jwtToken.replace(TOKEN_PREFIX, ""));
            return true;
        } catch (JwtException e) {
            System.err.println("JWT验证失败: " + e.getClass().getSimpleName() + " - " + e.getMessage());
            return false;
        }
    }

    // 从HttpServletRequest获取会员ID
    public static SysUser getMemberIdByJwtToken(HttpServletRequest request) {
        try {
            String authHeader = request.getHeader("Authorization");
            System.out.println("authHeader->" + authHeader);
            if (StringUtils.isEmpty(authHeader) || !authHeader.startsWith(TOKEN_PREFIX)) {
                System.out.println("getMemberIdByJwtToken不存在");
                throw new TokenException(ResultCodeEnum.TOKEN_LOGIN_AUTH);
            }
            String token = authHeader.replace(TOKEN_PREFIX, "");
            String id = parseToken(token).getBody().get("id", String.class);
            String name = parseToken(token).getBody().get("username", String.class);
            return new SysUser(Long.valueOf(id), name);
        } catch (JwtException e) {
            throw new TokenException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}